<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/11
 * Time: 14:07
 */

namespace bgb\weixin;

use bgb\Http;
use think\Log;

/**
 * 微信jssdk
 * Class Jssdk
 * @package bgb\weixin
 */
class Jssdk
{

    use Http;

    protected static $instance;

    const GET_JSAPI_TICKET_URL = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';

    protected $accessToken;
    protected $appid;
    protected $appsecret;

    /**
     * Jssdk constructor.
     * @param $appid
     * @param $appsecret
     */
    public function __construct($appid)
    {
        $tokenResult = file_get_contents('http://www.baigebao.com/home/api/getwxtoken?key=asfsfdsjdfnhaksdjjfaeifhadsfnhclksdanf213ds');

        $tokenResult = json_decode($tokenResult, true);

        if ($tokenResult['status'] == false) return false;

        $this->accessToken = ($tokenResult['data']['access_token']);;
        $this->appid = $appid;
    }

    /**
     * 单例支持
     * @param $appid
     * @param $appsecret
     * @return $this
     */
    public static function getInstance($appid, $appsecret)
    {
        $key = md5('appid:' . $appid . ':appsecret:' . $appsecret);

        if (!isset(self::$instance[$key])) {
            self::$instance[$key] = new static($appid, $appsecret);
        }

        return self::$instance[$key];

    }

    public function getSignPackage()
    {
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "{$protocol}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        Log::info('【微信jssdk】' . json_encode($signPackage, JSON_UNESCAPED_UNICODE));
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取jsapi ticket
     * @return mixed|string
     */
    private function getJsApiTicket()
    {
        $key = md5('jsapi:ticket:' . $this->accessToken);

        if (!$ticket = cache($key)) {
            $result = $this->getRequest(self::GET_JSAPI_TICKET_URL, [
                'type' => 'jsapi',
                'access_token' => $this->accessToken
            ]);
            Log::info('【微信jssdkticket】' . json_encode($result, JSON_UNESCAPED_UNICODE));
            $ticket = '';
            if (isset($result['ticket'])) {
                $ticket = $result['ticket'];
                cache($key, $ticket, 7000);
            }

        }

        return $ticket;
    }

}